package com.sms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.sms.common.Constants;
import com.sms.web.rest.RestObject;
import com.sms.web.system.entity.SysMenu;
import com.sms.web.system.entity.SysUser;

/**
 * @desc 权限拦截器 
 * @author WuJiangWu
 * @time 2018年5月7日下午7:26:39
 */
public class AuthInterceptor implements HandlerInterceptor {

	private static final Logger logger = Logger.getLogger(AuthInterceptor.class);

	/**
	 * 在controller后拦截
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception {

	}

	public void postHandle(	HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在controller前拦截
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String requestPath = getRequestPath(request);//访问url
		HttpSession session = request.getSession();
		logger.info("requestPath:"+requestPath);
		
		SysUser user = (SysUser) session.getAttribute(Constants.USER_SESSION_NAME);
		//超级管理员跳过签权
		String username = user.getUsername();
		if(StringUtils.isNotBlank(username) &&( username.equals("admin") || username.equals("superadmin") )) {
			return true;
		}
		for(SysMenu menu: user.getMenuList()) {
			if(menu.getMenuUrl().equals(requestPath)) {
				return true;
			}
		}
		//没有权限访问
        RestObject restobj = RestObject.newRestObject(RestObject.STATUS_CODE_FORBIDDEN, "权限不足禁止访问");
        //响应客户端
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.getWriter().print(JSONObject.toJSONString(restobj));
		return false;
	}
	
	/**
	 * 截取访问路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestPath(HttpServletRequest request) {

		String requestPath = request.getRequestURI();
		// 去掉其他参数
		if (requestPath.indexOf("&") > -1) {
			requestPath = requestPath.substring(0, requestPath.indexOf("&"));
		}
		// 去掉jsessionid参数
		if(requestPath.indexOf(";") > -1){
			requestPath = requestPath.substring(0, requestPath.indexOf(";"));
		}
		// 去掉项目路径
		requestPath = requestPath.substring(request.getContextPath().length());
		return requestPath;
	}
}
